package com.my.mymafengwo.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.smallstrong.mafengwopro.R;
import com.google.gson.Gson;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.db.sqlite.WhereBuilder;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ContentView;
import com.my.mymafengwo.adapter.SearchGridAdapter;
import com.my.mymafengwo.base.BaseActivity;
import com.my.mymafengwo.bean.SearchData;
import com.my.mymafengwo.utils.UrlUtils;
import com.my.mymafengwo.views.CustomEditText;

import java.util.ArrayList;
import java.util.List;


/**
 * ***********************************************
 * author:ljz
 * time:2015/12/3 11:25
 * name:首页搜索框点击后跳转的页面
 * step:
 * ***********************************************
 */

@ContentView(R.layout.activity_search)
public class SearchActivity extends BaseActivity implements AdapterView.OnItemClickListener, View.OnClickListener {
    private List<SearchData.DataEntity.ListEntity> list = new ArrayList<>();
    //国内热点数据
    private List<SearchData.DataEntity.ListEntity.ListEntity2> dataInland = new ArrayList<>();
    //国外热点数据
    private List<SearchData.DataEntity.ListEntity.ListEntity2> dataForeign = new ArrayList<>();
    //历史查询数据
    private List<SearchData.DataEntity.ListEntity.ListEntity2> dataHistory = new ArrayList<>();
    private GridView gridViewInland, gridViewForeign, gridViewHistory;
    //国内和国外适配器，历史查询适配器
    private SearchGridAdapter adapterInland, adapterForeign, adapterHistory;
    private ImageView ivHotInland, ivHotFroeign;
    private TextView tvHotInland, tvHotFroeign, tvBack, tvClearHistory;
    private CustomEditText customEditText;//自定义的控件
    private LinearLayout layout_history;
    private DbUtils dbUtils;
    public static final int VERSION = 1;//数据库版本

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */

    @Override
    protected void loadXml() {
        ViewUtils.inject(SearchActivity.this);
        DbUtils.DaoConfig db = new DbUtils.DaoConfig(this);
        db.setDbName("searchhistory.db");
        db.setDbVersion(VERSION);
        //版本更新时使用
        db.setDbUpgradeListener(new DbUtils.DbUpgradeListener() {
            @Override
            public void onUpgrade(DbUtils arg0, int arg1, int arg2) {
            }
        });
        //创建数据库
        dbUtils = DbUtils.create(db);
        try {
            //创建表
            dbUtils.createTableIfNotExist(SearchData.DataEntity.ListEntity.ListEntity2.class);
        } catch (DbException e) {
            e.printStackTrace();
        }
        adapterInland = new SearchGridAdapter(this);
        adapterForeign = new SearchGridAdapter(this);
        adapterHistory = new SearchGridAdapter(this);
    }


    @Override
    protected void getIntentData(Bundle savedInstanceState) {

    }

    /**
     * 找控件
     */
    @Override
    protected void initViews() {
        gridViewInland = (GridView) findViewById(R.id.gv_hot_internal);
        gridViewForeign = (GridView) findViewById(R.id.gv_hot_foreign);
        gridViewHistory = (GridView) findViewById(R.id.gv_history);
        ivHotInland = (ImageView) findViewById(R.id.iv_hot_internal);
        tvHotInland = (TextView) findViewById(R.id.tv_hot_internal);
        ivHotFroeign = (ImageView) findViewById(R.id.iv_hot_foreign);
        tvHotFroeign = (TextView) findViewById(R.id.tv_hot_foreign);
        tvBack = (TextView) findViewById(R.id.tv_back);
        layout_history = (LinearLayout) findViewById(R.id.layout_history);
        tvClearHistory = (TextView) findViewById(R.id.tv_clear_history);
        customEditText = (CustomEditText) findViewById(R.id.custom_et);
    }

    /**
     * 设置监听
     */
    @Override
    protected void registerListener() {
        tvBack.setOnClickListener(this);
        tvClearHistory.setOnClickListener(this);
        gridViewInland.setOnItemClickListener(this);
        gridViewForeign.setOnItemClickListener(this);
        gridViewHistory.setOnItemClickListener(this);
        customEditText.setOnClickListener2(new CustomEditText.MyOnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(SearchActivity.this,StartSearchActivity.class);
                intent.putExtra("hint","搜索目的地 攻略 景点 酒店等");
                startActivity(intent);
            }
        });
    }

    /**
     * 加载数据
     */
    @Override
    protected void initData() {
        HttpUtils get = new HttpUtils();
        get.send(HttpRequest.HttpMethod.GET, UrlUtils.SEARCH_URL_JUMP,
                new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        // 当前连网结果
                        String result = responseInfo.result;
                        //Gson解析
                        Gson gson = new Gson();
                        SearchData bean = gson.fromJson(result, SearchData.class);
                        list = bean.getData().getList();

                        dataInland = list.get(0).getList();
                        dataForeign = list.get(1).getList();

                        adapterInland.setData(dataInland);
                        adapterForeign.setData(dataForeign);
                        adapterInland.notifyDataSetChanged();
                        adapterInland.notifyDataSetChanged();

                        tvHotInland.setText(list.get(0).getName());
                        tvHotFroeign.setText(list.get(1).getName());

                        String iconInland = list.get(0).getIcon();
                        String iconForeign = list.get(1).getIcon();
                        BitmapUtils bm = new BitmapUtils(SearchActivity.this);
                        bm.display(ivHotInland, iconInland);
                        bm.display(ivHotFroeign, iconForeign);
                    }

                    @Override
                    public void onFailure(HttpException e, String s) {

                    }
                });


        gridViewInland.setAdapter(adapterInland);
        gridViewForeign.setAdapter(adapterForeign);

    }

    @Override
    protected void onResume() {
        super.onResume();
        findDb();
        //设置适配器
        gridViewHistory.setAdapter(adapterHistory);
    }

    /**
     * 添加表格数据并跳转页面
     *
     * @param data
     * @param position
     */
    private void insertDb(List<SearchData.DataEntity.ListEntity.ListEntity2> data, int position) {
        String name = data.get(position).getName();
        List<SearchData.DataEntity.ListEntity.ListEntity2> list = findDbByName(name);
        try {
            if (dataHistory.size() < 10) {
                if (list.size() == 0) {
                    dbUtils.save(new SearchData.DataEntity.ListEntity.ListEntity2(name, data.get(position).getJump_url()));
                } else {
                    dbUtils.delete(SearchData.DataEntity.ListEntity.ListEntity2.class, WhereBuilder.b("name", "=", name));
                    dbUtils.save(new SearchData.DataEntity.ListEntity.ListEntity2(name, data.get(position).getJump_url()));
                }
            } else {
                dataHistory.remove(0);
                dbUtils.delete(SearchData.DataEntity.ListEntity.ListEntity2.class, WhereBuilder.b("_id", ">", -1));
                for (int i = 0; i < dataHistory.size(); i++) {
                    dbUtils.save(dataHistory.get(i));
                }
                dbUtils.save(new SearchData.DataEntity.ListEntity.ListEntity2(name, data.get(position).getJump_url()));
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
        Intent intent = new Intent(SearchActivity.this, TravelNotesActivity.class);
        intent.putExtra("url", data.get(position).getJump_url());
        startActivity(intent);
    }

    /**
     * 查询表格里所有的数据
     */
    private void findDb() {
        try {
            //查询表格得到数据
            dataHistory.clear();
            List<SearchData.DataEntity.ListEntity.ListEntity2> list = dbUtils.findAll(SearchData.DataEntity.ListEntity.ListEntity2.class);
            dataHistory.addAll(list);
//            dataHistory=dbUtils.findAll(SearchData.DataEntity.ListEntity.ListEntity2.class);
            if (dataHistory.size() != 0) {
                layout_history.setVisibility(View.VISIBLE);
            } else {
                layout_history.setVisibility(View.GONE);
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
        adapterHistory.setData(dataHistory);
        adapterHistory.notifyDataSetChanged();
    }

    /**
     * 根据姓名查询表格里的数据
     */
    private List<SearchData.DataEntity.ListEntity.ListEntity2> findDbByName(String name) {
        List<SearchData.DataEntity.ListEntity.ListEntity2> list = new ArrayList<>();
        try {
            list = dbUtils.findAll(Selector.from(SearchData.DataEntity.ListEntity.ListEntity2.class).where("name", "=", name));
        } catch (DbException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * gridview点击事件
     *
     * @param parent
     * @param view
     * @param position
     * @param id
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (parent.getId()) {
            case R.id.gv_hot_internal:
                insertDb(dataInland, position);
                break;
            case R.id.gv_hot_foreign:
                insertDb(dataForeign, position);
                break;
            case R.id.gv_history:
                insertDb(dataHistory, position);
                break;
            default:
                break;
        }

    }

    /**
     * 点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_back:
                finish();
                break;
            case R.id.tv_clear_history:
                try {
                    dbUtils.delete(SearchData.DataEntity.ListEntity.ListEntity2.class, WhereBuilder.b("_id", ">", -1));
                    findDb();
                } catch (DbException e1) {
                    e1.printStackTrace();
                }
                break;
            default:
                break;
        }
    }
}